package com.sk.util.model;

import com.sk.util.SecurityUtil;
import lombok.SneakyThrows;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * md5输入流监控
 *
 * @author smy
 * {@code @date} 2022/11/20
 */
public class Md5InputStream extends InputStream {
    private final InputStream is;
    private final MessageDigest md5;
    private long size;

    @SneakyThrows
    public Md5InputStream(InputStream is) {
        this.is = is;
        md5 = MessageDigest.getInstance("MD5");
    }

    public String md5() {
        return SecurityUtil.toHex(md5.digest());
    }

    public long size() {
        return size;
    }

    @Override
    public int read() throws IOException {
        int b = is.read();
        size += 1;
        md5.update((byte) b);
        return b;
    }


    @Override
    public int available() throws IOException {
        return is.available();
    }

    @Override
    public void close() throws IOException {
        is.close();
    }

    @Override
    public synchronized void mark(int readLimit) {
        is.mark(readLimit);
    }

    @Override
    public synchronized void reset() throws IOException {
        is.reset();
    }

    @Override
    public boolean markSupported() {
        return is.markSupported();
    }
}
